//
//  ProjectExecuteAnalysisViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/12/18.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit

class ProjectExecuteAnalysisViewController: RefreshedTableViewController,SearchCondition,UIPickerViewDelegate,UIPickerViewDataSource {
    func search(with orgcode: String?, yearmonth: String?, projname: String?) {
        
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 2
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        if row == 0 {
            let label = self.label(with: "升序")
            return label
        } else {
            let label = self.label(with: "降序")
            return label
        }
    }
    
    var order = 1 //1升序 0将序
    
    override func endedit() {
        let index = picker.selectedRow(inComponent: 0)
        if index == 0 {
            //升序
            order = 1
            self.ratio.inc()
            self.beginRefresh()
        } else {
            //降序
            order = 0
            self.ratio.dec()
            self.beginRefresh()
        }
        super.endedit()
    }
    
    func search(with orgcode: String?, year: Int?, projname: String?) {
        let searchButton = UIBarButtonItem.init(image: UIImage(named: "icon_nav_search2")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(searchAction))
        self.navigationItem.rightBarButtonItem = searchButton
        if (orgcode?.count ?? 0) > 0 {
            self.orgCode = orgcode!
            let targetitem = self.companys.filter { (json) -> Bool in
                return json.contents?["code"]?.rawString() == self.orgCode
            }
            if targetitem.count > 0 {
                let item = targetitem[0]
                self.searchsHeader.orgField.text = item.contents?["name"]?.rawString()
            }
        }
        if (year ?? 0) > 0 {
            self.searchsHeader.yearField.text = String(year!)
        } else {
            self.searchsHeader.yearField.text = ""
        }
        if (projname?.count ?? 0) > 0 {
            self.searchsHeader.projectNameField.text = projname!
        } else {
            self.searchsHeader.projectNameField.text = ""
        }
        self.page = 1
        self.beginRefresh()
    }
    
    override func reset() {
        let searchButton = UIBarButtonItem.init(image: UIImage(named: "icon_nav_search2")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(searchAction))
        self.navigationItem.rightBarButtonItem = searchButton
        self.orgCode = ""
        self.searchsHeader.yearField.text = nil
        self.searchsHeader.projectNameField.text = nil
        self.tableView.reloadData()
        self.page = 1
        self.beginRefresh()
        //加载数据
    }
    
    
    override func param(for name: String) -> Dictionary<String, Any> {
        var dic: [String: Any] = [:]
        dic["rank"] = String(order)
        if self.orgCode.count > 0 {
            dic["projectApplyOrgCode"] = self.orgCode
        }
        if (self.searchsHeader.yearField.text?.count ?? 0) > 0 {
            dic["year"] = searchsHeader.yearField.text!
        }
        if (self.searchsHeader.projectNameField.text?.count ?? 0) > 0 {
            dic["gsProjName"] = self.searchsHeader.projectNameField.text!
        }
        return dic + super.param(for: name)
    }
    
    override func path(for name: String) -> String {
        return ProjectExecuteAnalysis
    }
    
    @objc override func searchAction()->Void{
        
        if self.presentedViewController == nil {
            let button = UIBarButtonItem.init(title: "取消", style: .plain, target: self, action: #selector(searchAction))
            self.navigationItem.rightBarButtonItem = button
            let search = ConditionSelectViewController()
            search.companys = self.companys
            search.delegate = self
            search.selectedOrg = self.orgCode
            if (self.searchsHeader.yearField.text?.count ?? 0) > 0 {
                search.year = Int((self.searchsHeader.yearField.text ?? "")) ?? 2018
            }
            if (self.searchsHeader.projectNameField.text?.count ?? 0) > 0 {
                search.projectname = self.searchsHeader.projectNameField.text ?? ""
            }
            self.present(vc: search)
        } else {
            let searchButton = UIBarButtonItem.init(image: UIImage(named: "icon_nav_search2")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(searchAction))
            self.navigationItem.rightBarButtonItem = searchButton
            self.presentedViewController?.dismiss()
        }
    }
    
    let searchsHeader = Bundle.main.loadNibNamed("ProjectConditionHeader", owner:nil, options: nil)?[0] as! ProjectConditionHeader
    let ratio = Bundle.main.loadNibNamed("RatioView", owner: nil, options: nil)?[0] as! RatioView
    
    @objc func selectorder()->Void{
        self.field.becomeFirstResponder()
    }
    
    let field = UITextField()
    let picker = UIPickerView.init(frame: CGRect.init(origin: .zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 220)))
    
    override func orgblock() {
        self.orgCode = ""
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.hidesBackButton = true
        self.ratio.dec()
        self.title = "项目执行分析"
        self.view.addSubview(field)
        picker.delegate = self
        picker.dataSource = self
        picker.backgroundColor = UIColor.white
        field.inputView = picker
        field.inputAccessoryView = self.toolbarview
        ratio.button.addTarget(self, action: #selector(selectorder), for: .touchUpInside)
        let back = UIBarButtonItem.init(image: UIImage.init(named: "icon_nav_whiteback")!, style: .plain, target: self, action: #selector(popobjc))
        back.tintColor = .white
        self.navigationItem.leftBarButtonItem = back
        let searchButton = UIBarButtonItem.init(image: UIImage(named: "icon_nav_search2")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(searchAction))
       self.navigationItem.rightBarButtonItem = searchButton
        self.navigationController?.navigationBar.setBackgroundImage(UIColor.hex("2b89df").image(size: CGSize(width: UIScreen.main.bounds.size.width, height: 64)), for: .default)
        self.navigationController?.navigationBar.tintColor = .white
        self.tableView.separatorInset = .zero
        self.tableView.register(UINib.init(nibName: "ExecuteAnalysisCell", bundle: Bundle.main), forCellReuseIdentifier: "ExecuteAnalysisCell")
    }
    
    var partialheadershow: Bool{
        get{
            let orgresult = self.orgCode.count > 0
            let year = (self.searchsHeader.yearField.text?.count ?? 0) > 0
            let projectname = (self.searchsHeader.projectNameField.text?.count ?? 0) > 0
            return orgresult || year || projectname
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "ExecuteAnalysisCell")!
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.partialheadershow == false {
            return 40
        } else {
            return 80
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.source.count
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if let cel = cell as? ExecuteAnalysisCell {
            cel.model = self.source[indexPath.row]
        }
    }
    
    func label(with title: String)->UILabel{
        let label = UILabel()
        label.textColor = UIColor.hex("333333")
        label.text = title
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .center
        label.backgroundColor = UIColor.white
        return label
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.tableSeparator
        if self.partialheadershow == true {
            view.addSubview(searchsHeader)
            searchsHeader.snp.makeConstraints { (make) in
                make.top.equalToSuperview()
                make.left.equalToSuperview()
                make.width.equalToSuperview()
                make.height.equalTo(40)
            }
            searchsHeader.delegate = self
        }
        let stack = UIStackView()
        stack.alignment = .fill
        stack.distribution = .fillEqually
        view.addSubview(stack)
        stack.spacing = 1
        stack.snp.makeConstraints { (make) in
            if self.partialheadershow == true {
                make.top.equalToSuperview().offset(41)
            } else {
                make.top.equalToSuperview().offset(1)
            }
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-1)
        }
        let titles = ["合同额(万元)","开票收入(万元)","成本合计(万元)"]
        for item in titles {
            let label = self.label(with: item)
            stack.addArrangedSubview(label)
        }
        stack.addArrangedSubview(self.ratio)
        return view
    }
    

    

}
